package com.mumu.xiaodu

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import java.text.SimpleDateFormat
import java.util.*

class HistoryAdapter(
    private val onHistoryClick: (HistoryItem) -> Unit
) : RecyclerView.Adapter<HistoryAdapter.HistoryViewHolder>() {
    
    private var history = mutableListOf<HistoryItem>()
    private val dateFormat = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
    
    fun updateHistory(newHistory: List<HistoryItem>) {
        history.clear()
        history.addAll(newHistory)
        notifyDataSetChanged()
    }
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_history, parent, false)
        return HistoryViewHolder(view)
    }
    
    override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
        holder.bind(history[position])
    }
    
    override fun getItemCount(): Int = history.size
    
    inner class HistoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val tvTitle: TextView = itemView.findViewById(R.id.tvTitle)
        private val tvUrl: TextView = itemView.findViewById(R.id.tvUrl)
        private val tvTime: TextView = itemView.findViewById(R.id.tvTime)
        
        fun bind(historyItem: HistoryItem) {
            tvTitle.text = historyItem.title
            tvUrl.text = historyItem.url
            tvTime.text = dateFormat.format(Date(historyItem.timestamp))
            
            itemView.setOnClickListener {
                onHistoryClick(historyItem)
            }
            
            // 设置焦点样式
            itemView.setOnFocusChangeListener { _, hasFocus ->
                if (hasFocus) {
                    itemView.setBackgroundResource(R.drawable.bookmark_item_focused)
                } else {
                    itemView.setBackgroundResource(R.drawable.bookmark_item_normal)
                }
            }
        }
    }
} 